package mobi.greenplate.theweb.repository;

import mobi.greenplate.theweb.domain.Address;
import java.util.List;
import java.util.ArrayList;
import javax.annotation.security.RolesAllowed;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("addressRepository")
public class AddressRepository {

    private EntityManager entityManager;

    @PersistenceContext
    void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public void delete(Long id) {
        final Address forDelete = entityManager.getReference(Address.class, id);
        entityManager.remove(forDelete);
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public Address save(Address address) {        
        return entityManager.merge(address);
    }
    
    @RolesAllowed(value = {"ROLE_USER"})
    public Address findById(Long id) {
        final Address address = entityManager.find(Address.class, id);
        if(null==address){
            throw new IllegalArgumentException("address with id="+id+" not found");
        }
        return address;        
    }

    public int countAll() {
        return ((Integer) entityManager.createQuery("SELECT count(o) from Address o").
                getSingleResult()).intValue();
    }

    @RolesAllowed(value = {"ROLE_USER"})
    @Transactional
    public List<Address> findAll(int firstResult, int maxResult) {
        final List<Address> founded = entityManager.createQuery("SELECT o FROM Address o").
                setFirstResult(firstResult).
                setMaxResults(maxResult).getResultList();
        return new ArrayList<Address>(founded);
    }
    


    
    
}
